package com.aizhixin.lab.project.course.service;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.company.domain.AccountDomain;
import com.aizhixin.lab.company.service.UserService;
import com.aizhixin.lab.course.classes.dto.CourseClassDTO;
import com.aizhixin.lab.project.course.domain.*;
import com.aizhixin.lab.project.course.entity.ProjectClass;
import com.aizhixin.lab.project.course.entity.ProjectClassStu;
import com.aizhixin.lab.project.course.entity.ProjectGroup;
import com.aizhixin.lab.project.course.repository.ProjectClassRepository;
import com.aizhixin.lab.project.course.repository.ProjectClassStuRepository;
import com.aizhixin.lab.project.course.vo.ProjectClassVo;
import com.aizhixin.lab.project.course.repository.ProjectGroupRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ProjectClassService {
    @Autowired
    private ProjectClassRepository classRepository;
    @Autowired
    private ProjectClassStuRepository stuRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProjectGroupRepository projectGroupRepository;
    /**
     * @param
     * @param accountDTO
     * @return
     */
    public Map<String, Object> addProjectClass(List<AddProjectClassDomain> classDomainList, AccountDTO accountDTO) {
        Map<String, Object> result = new HashMap<>();
        List<ProjectClassStu> classStuList = new ArrayList<>();
        List<ProjectClass> classes=new ArrayList<>();
        for (AddProjectClassDomain domain:classDomainList) {
            ProjectClass projectClass = new ProjectClass();
            projectClass.setDeleteFlag(DataValidity.VALID.getState());
            projectClass.setCreatedBy(accountDTO.getId());
            projectClass.setProjectId(domain.getProjectId());
            if (StringUtils.isEmpty(domain.getProjectId())) {
                result.put(ApiReturnConstants.ERROR, "项目id不能为空！");
                result.put(ApiReturnConstants.SUCCESS, false);
                return result;
            }
            if (domain.getClassId() != null) {
                System.out.println(domain.getClassId());
//                Integer classNum = classRepository.countByProjectIdAndClassIdAndDeleteFlag(domain.getProjectId(), domain.getClassId(), DataValidity.VALID.getState());
//                if (classNum > 0) {
//                    result.put(ApiReturnConstants.ERROR, "班级已添加,请勿重复添加！");
//                    result.put(ApiReturnConstants.SUCCESS, false);
//                    return result;
//                }
                projectClass.setClassId(domain.getClassId());
                projectClass.setProfessionalId(domain.getProfessionalId());
                projectClass.setCollegeId(domain.getCollegeId());
                projectClass.setId(UUID.randomUUID().toString());
                projectClass.setProjectId(domain.getProjectId());
                projectClass.setTeacherId(accountDTO.getId());
                List<Long> stuIds = userService.getUserIdByClassId(domain.getClassId());
                projectClass.setStuNum(stuIds.size());
                Integer countStu = stuRepository.countByProjectIdAndStuIdInAndDeleteFlag(domain.getProjectId(), stuIds, DataValidity.VALID.getState());
                if (countStu > 0) {
                    result.put(ApiReturnConstants.ERROR, "该班级中已有学生添加在其他班级中！");
                    result.put(ApiReturnConstants.SUCCESS, false);
                    return result;
                }
                for (Long l : stuIds) {
                    ProjectClassStu projectClassStu = new ProjectClassStu();
                    projectClassStu.setId(UUID.randomUUID().toString());
                    projectClassStu.setProjectClassId(projectClass.getId());
                    projectClassStu.setStuId(l);
                    projectClassStu.setDeleteFlag(DataValidity.VALID.getState());
                    projectClassStu.setUrgeNum(0);
                    projectClassStu.setLikeNum(0);
                    projectClassStu.setProjectId(domain.getProjectId());
                    projectClassStu.setCreatedBy(accountDTO.getId());
                    projectClassStu.setRole("member");
                    classStuList.add(projectClassStu);
                }

            } else if (domain.getUserIds() == null || domain.getUserIds().size() == 0) {
                result.put(ApiReturnConstants.DATA, "学生Id和班级ID不能同时为空！");
                result.put(ApiReturnConstants.SUCCESS, true);
                return result;
            } else if (domain.getUserIds().size() > 0) {
                Integer countStu = stuRepository.countByProjectIdAndStuIdInAndDeleteFlag(domain.getProjectId(), domain.getUserIds(), DataValidity.VALID.getState());
                if (countStu > 0) {
                    result.put(ApiReturnConstants.ERROR, "学生已存在！");
                    result.put(ApiReturnConstants.SUCCESS, false);
                    return result;
                }
                projectClass = classRepository.findOne(domain.getId());
                if (Objects.isNull(projectClass)) {
                    if (countStu > 0) {
                        result.put(ApiReturnConstants.ERROR, "找不到改班级！");
                        result.put(ApiReturnConstants.SUCCESS, false);
                        return result;
                    }
                }
                for (Long l : domain.getUserIds()) {
                    ProjectClassStu projectClassStu = new ProjectClassStu();
                    projectClassStu.setId(UUID.randomUUID().toString());
                    projectClassStu.setProjectClassId(projectClass.getId());
                    projectClassStu.setStuId(l);
                    projectClassStu.setDeleteFlag(0);
                    projectClassStu.setCreatedBy(accountDTO.getId());
                    classStuList.add(projectClassStu);
                }
                projectClass.setStuNum(projectClass.getStuNum() + domain.getUserIds().size());
            }
            classes.add(projectClass);
        }
        classRepository.save(classes);
        stuRepository.save(classStuList);
        result.put(ApiReturnConstants.DATA, "添加成功！");
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }


    public Map<String, Object> addPracticeProjectClass(String projectIds,Long teaId,String parentId, AccountDTO accountDTO) {
        Map<String, Object> result = new HashMap<>();
        List<ProjectClassStu> classStuList = new ArrayList<>();
        List<ProjectClass> classes = new ArrayList<>();
        String[] pj = projectIds.split(",");
        for (String projectId : pj) {
            ProjectClass projectClass = new ProjectClass();
            projectClass.setDeleteFlag(DataValidity.VALID.getState());
            projectClass.setCreatedBy(accountDTO.getId());
            projectClass.setProjectId(projectId);
            if (StringUtils.isEmpty(projectId)) {
                result.put(ApiReturnConstants.ERROR, "项目id不能为空！");
                result.put(ApiReturnConstants.SUCCESS, false);
                return result;
            }
            ProjectClassStu classStu = stuRepository.findByProjectIdAndStuIdAndDeleteFlag(parentId, accountDTO.getId(), 0);
            List<ProjectClassStu> projectClassStusList = stuRepository.findByProjectIdAndGroupIdAndDeleteFlag(projectId,classStu.getGroupId(),0);
            if(projectClassStusList.size()>0){
                result.put(ApiReturnConstants.ERROR, "不能重复加入项目");
                result.put(ApiReturnConstants.SUCCESS, false);
                return result;
            }
            if (accountDTO.getClassId() != null) {
                projectClass.setClassId(accountDTO.getClassId());
                projectClass.setProfessionalId(accountDTO.getProfessionalId());
                projectClass.setCollegeId(accountDTO.getCollegeId());
                projectClass.setId(UUID.randomUUID().toString());
                projectClass.setProjectId(projectId);
                projectClass.setTeacherId(teaId);
                List<ProjectClassStu> projectClassStuList = stuRepository.findByProjectIdAndGroupIdAndDeleteFlag(parentId, classStu.getGroupId(), 0);
                List<Long> stuIds = projectClassStuList.stream().map(ProjectClassStu::getStuId).collect(Collectors.toList());
                projectClass.setStuNum(stuIds.size());
                for (Long l : stuIds) {
                    ProjectClassStu projectClassStu = new ProjectClassStu();
                    projectClassStu.setId(UUID.randomUUID().toString());
                    projectClassStu.setProjectClassId(projectClass.getId());
                    projectClassStu.setStuId(l);
                    projectClassStu.setDeleteFlag(DataValidity.VALID.getState());
                    projectClassStu.setUrgeNum(0);
                    projectClassStu.setLikeNum(0);
                    projectClassStu.setProjectId(projectId);
                    projectClassStu.setCreatedBy(accountDTO.getId());
                    if (l.equals(accountDTO.getId())){
                        projectClassStu.setRole("leader");
                    }else {
                        projectClassStu.setRole("member");
                    }
                    projectClassStu.setGroupId(classStu.getGroupId());
                    projectClass.setGroupId(classStu.getGroupId());

                    classStuList.add(projectClassStu);
                }

            }
            classes.add(projectClass);
        }
        classRepository.save(classes);
        stuRepository.save(classStuList);
        result.put(ApiReturnConstants.DATA, "添加成功！");
        result.put(ApiReturnConstants.SUCCESS, true);
        return result;
    }

    RowMapper<ProjectStuDomain> rm2 = new RowMapper<ProjectStuDomain>() {

        @Override
        public ProjectStuDomain mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            ProjectStuDomain domain = new ProjectStuDomain();
            domain.setId(rs.getString("ID"));
            domain.setCollegeId(rs.getLong("COLLEGE_ID"));
            domain.setProfessionalId(rs.getLong("PROFESSIONAL_ID"));
            domain.setJobNum(rs.getString("JOB_NUM"));
            domain.setSex(rs.getString("SEX"));
            domain.setCollegeName(rs.getString("COLLEGE_NAME"));
            domain.setProfessionalName(rs.getString("PROFESSIONAL_NAME"));
            domain.setName(rs.getString("NAME"));
            domain.setPhone(rs.getString("PHONE"));
            domain.setEmail(rs.getString("EMAIL"));
            domain.setClassId(rs.getLong("CLASS_ID"));
            domain.setClassName(rs.getString("CLASS_NAME"));
            domain.setDeleteFlag(rs.getInt("DELETE_FLAG"));
            domain.setUserName(rs.getString("user_name"));
            Set<String> keys = redisTemplate.keys(domain.getUserName() + ":" + "*");
            if (keys.size() > 0) {
                domain.setIsRun(true);
            } else {
                domain.setIsRun(false);
            }
            return domain;
        }
    };

    /**
     * 查看课程下的学生列表
     *
     * @param domain
     * @return
     */
    public Map<String, Object> getStuPage(QueryProjectClassDomain domain) {
        String sql = "SELECT ccs.ID,U.NAME,PHONE,u.user_name,EMAIL,JOB_NUM,SEX,c.NAME AS COLLEGE_NAME,p.NAME AS PROFESSIONAL_NAME,u.DELETE_FLAG,u.COLLEGE_ID,u.PROFESSIONAL_ID,u.CLASS_ID,cl.name as CLASS_NAME from `c_project_class_stu` ccs LEFT JOIN  `t_user` u  ON  u.id =ccs.stu_id left join `t_college` c on u.COLLEGE_ID = c.id LEFT JOIN `t_professional` p ON u.PROFESSIONAL_ID = p.ID left join `t_classes` cl on u.class_id =cl.id where ccs.delete_flag = 0 ";
        String countSql = "SELECT count(*) from `c_project_class_stu` ccs LEFT JOIN  `t_user` u  ON  u.id =ccs.stu_id left join `t_college` c on u.COLLEGE_ID = c.id LEFT JOIN `t_professional` p ON u.PROFESSIONAL_ID = p.ID left join `t_classes` cl on u.class_id =cl.id where ccs.delete_flag = 0 ";
        if (!StringUtils.isEmpty(domain.getProjectId())){
            sql+=" AND ccs.project_id='"+domain.getProjectId()+"' ";
            countSql+=" AND ccs.project_id='"+domain.getProjectId()+"' ";
        }
        if (!StringUtils.isEmpty(domain.getProjectClassId())){
            sql+=" AND ccs.project_class_id='"+domain.getProjectClassId()+"' ";
            countSql+=" AND ccs.project_class_id='"+domain.getProjectClassId()+"' ";
        }
        if(!StringUtils.isEmpty(domain.getStuName())){
            sql+="AND u.name like '%"+domain.getStuName()+"%'";
            countSql+="AND u.name like '%"+domain.getStuName()+"%' ";
        }
        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("u.ID");
        dto.setAsc(true);
        sort.add(dto);
        return pageJdbcUtil.getPageInfor(domain.getPageSize(),
                domain.getPageNumber(), rm2, sort, sql, countSql);
    }

    RowMapper<ProjectClassVo> rm = new RowMapper<ProjectClassVo>() {

        @Override
        public ProjectClassVo mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            ProjectClassVo dto = new ProjectClassVo();
            dto.setProjectId(rs.getString("project_id"));
            dto.setProjectClassId(rs.getString("id"));
            dto.setCollegeName(rs.getString("college_name"));
            dto.setClassName(rs.getString("class_name"));
            dto.setClassId(rs.getLong("class_id"));
            dto.setCollegeId(rs.getLong("college_id"));
            dto.setStuNum(rs.getInt("stu_num"));
            if (!StringUtils.isEmpty(rs.getString("group_name"))){
                dto.setClassName(dto.getClassName()+"-"+rs.getString("group_name"));
            }
            return dto;
        }
    };

    /**
     * 查询项目下所有班级
     * @param projectId
     * @return
     */
    public List<ProjectClassVo> findProjectClass(String projectId) {
        String sql = "SELECT cc.`id`,cc.project_id,cc.class_id,cl.`name` AS class_name,cc.college_id,co.`name` AS college_name,cc.stu_num,cg.group_name FROM `c_project_class` cc LEFT JOIN `t_college` co ON cc.COLLEGE_ID = co.ID LEFT JOIN `t_classes` cl ON cc.CLASS_ID = cl.ID LEFT JOIN c_project_group cg ON cg.id=cc.group_id WHERE  cc.delete_flag = 0 AND cc.project_id ='" + projectId + "' AND (cg.delete_flag=0 or cg.delete_flag is null) order by cc.created_date,cc.project_id desc";
        return pageJdbcUtil.getInfo(sql, rm);
    }


    public ProjectGroup stuCreationGroup(StuCreationGroupDomain domain){
        ProjectGroup projectGroup = new ProjectGroup();
        projectGroup.setId(UUID.randomUUID().toString());
        projectGroup.setProjectId(domain.getProjectId());
        projectGroup.setGroupNum(domain.getGroupNum());
        projectGroup.setGroupName(domain.getGroupName());
        projectGroup.setCreatedDate(new Date());
        projectGroup.setMaxNum(domain.getMaxNum());
        projectGroup.setDeleteFlag(0);
        return projectGroupRepository.save(projectGroup);
    }




}
